﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StayInTouch.Core.Helpers
{
    public static class FuzzyStringComparer
    {
        public static float FuzzyCompare(string s1, string s2)
        { 
            int maxLength = Math.Max(s1.Length, s2.Length);
            if (s1.Length < s2.Length) {s1 = s1 + (new string(' ', (s2.Length - s1.Length))); }
            else {s2 = s2 + (new string(' ', (s1.Length - s2.Length))); }
            float res = 0;
            for (int i = 1; i <= maxLength; i++)
            {
                res = res + FuzzyDiff(s1, s2, i);
            }

            return (res / maxLength);
        }

        private static float FuzzyDiff(string s1, string s2, int n)
        {
            if (s1.Length == n) { return FuzzyCompareParts(s1, s2); }
            else
            {
                float res = 0;
                for (int i = 0; i < s1.Length - n; i++)
                {
                    res = res + FuzzyCompareParts(s1.Substring(i, n), s2.Substring(i, n));
                }

                return res / (s1.Length - n);
            }
        }



        private static float FuzzyCompareParts(string s1, string s2)
        {
            List<char> list = s1.ToList();
            
            int res = 0;
            for (int i = 0; i < s1.Length; i++)
            {
                if (!list.Contains(s2[i]))
                {
                    res++;
                }
                else
                {
                    list.RemoveAt(list.IndexOf(s2[i]));
                }
            }
            return res/s2.Length;
        }
    }

}
